package com.lt.lumentracks.service.Impl;

import com.lt.lumentracks.constant.ErrorConstant.ChatErrorConstant;
import com.lt.lumentracks.entity.po.Conversation;
import com.lt.lumentracks.entity.po.ConversationUser;
import com.lt.lumentracks.exception.BaseException;
import com.lt.lumentracks.mapper.ConversationMapper;
import com.lt.lumentracks.service.IConversationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.lumentracks.service.IConversationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 会话表 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-10-06
 */
@Service
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements IConversationService {

    @Autowired
    private IConversationUserService iConversationUserService;
    @Autowired
    private ConversationMapper conversationMapper;


    /** 新增会话
     * @param conv 会话实体类
     * @param receiverId 接收者id，只有第一次创建，且会话类型是单聊时才需要传
     * @return 新增会话的id
     */
    @Override
    @Transactional
    public Long addConversation(Conversation conv, Integer receiverId) {
        if(conv.getConversationType() == 1 && receiverId == null){
            throw new BaseException(ChatErrorConstant.CONVERSATION_ADD_PRIVATE_CHAT_ARG_ERROR);
        }

        // 1.【会话表】新增
        conv.setCreateTime(LocalDateTime.now());
        this.save(conv);

        // 2.【会话成员表】新增
        List<ConversationUser> cu_list = new ArrayList<>();

        // 2.1.如果是单聊，则将接收者加入【会话成员表】
        if(conv.getConversationType() == 1 && receiverId != null){
            // 如果存在这俩的单聊，则不能再次创建，抛出异常，回滚
            boolean singleChatExists = iConversationUserService.isSingleChatExists(conv.getCreateBy(), receiverId);
            if(singleChatExists){
                throw new BaseException("用户" + conv.getCreateBy() + "与" + receiverId + "的 " + ChatErrorConstant.CONVERSATION_ADD_PRIVATE_CHAT_EXISTED);
            }

            ConversationUser cu_r = new ConversationUser();
            cu_r.setConversationId(conv.getId());
            cu_r.setUserId(receiverId);
            cu_r.setCreateTime(LocalDateTime.now());

            cu_list.add(cu_r);
        }

        // 2.2.将创始人加入【会话成员表】
        ConversationUser cu = new ConversationUser();
        cu.setConversationId(conv.getId());
        cu.setUserId(conv.getCreateBy());
        cu.setCreateTime(LocalDateTime.now());

        cu_list.add(cu);

        iConversationUserService.saveBatch(cu_list);
        return conv.getId();
    }


    // 查询当前用户所加入的会话（返回Conversation类型的集合）
    @Override
    public List<Conversation> queryRawByUser(Integer userId) {
        return conversationMapper.queryRawByUser(userId);
    }

}
